package com.google.code;

import java.text.DecimalFormat;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class mainScreen extends Activity 
{
	static Socket socket;
	static String ip;
	static TextView curTemp;
	static TextView desTemp;
	static Handler curTempHandler;
	static Handler desTempHandler;
	
	public void onCreate(Bundle savedInstance)
	{
		super.onCreate(savedInstance); 
		setContentView(R.layout.templayout);
		this.ip = "";
		curTemp = (TextView)findViewById(R.id.textCurTempValue);
		curTemp.setText("Getting current temp...");
		desTemp = (TextView)findViewById(R.id.textDesiredTempValue);
		desTemp.setText("80"); 
		Button increaseButton = (Button)findViewById(R.id.buttonIncrease);
		Button decreaseButton = (Button)findViewById(R.id.buttonDecrease); 
        increaseButton.setOnClickListener(new OnClickListener()  
        {
        	public void onClick(View v) 
        	{
        		socket.sendMessage(""+(Double.parseDouble(desTemp.getText().toString())+1));
        	}
        }); 
        
        decreaseButton.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View v) 
        	{
        		socket.sendMessage(""+(Double.parseDouble(desTemp.getText().toString())-1));
        	}
        });
        
		curTempHandler = new Handler();
		desTempHandler = new Handler();
		Bundle extras = getIntent().getExtras();
		if(extras !=null) { 
			this.ip = extras.getString("IP_ADDRESS");  
		}
		Log.d("THERM", this.ip);
		if(ip != "")
			socket = new Socket(ip,8877);
	}
	
	public static void setCurTemp(final double temp)
	{
		curTempHandler.post(new Runnable() {
			public void run() {
				if(curTemp != null)
					curTemp.setText(""+roundTwoDecimals(temp));
				else
					Log.d("THERM", "Cur temp is not declared properly");
			}
		});
	}
	
	public static double roundTwoDecimals(double d) {
	    DecimalFormat twoDForm = new DecimalFormat("#.##");
	    return Double.valueOf(twoDForm.format(d));
	}
	
	public static void setDesiredTemp(final double temp)
	{
		desTempHandler.post(new Runnable() {
			public void run() {
				desTemp.setText(""+temp);
			}
		});
	}
}
